package com.eagle.gennewdata;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import com.eagle.gennewdata.model.NewDaoFactory;
import com.eagle.gennewdata.model.NewRssItem;
import com.eagle.gennewdata.model.WebSetting;
import com.eagle.gennewdata.untl.GlobalsFun;
import com.eagle.gennewdata.untl.ZLibUtils;

@SuppressWarnings("serial")
public class ListNewDataServlet extends HttpServlet {
	public static boolean s_bIsRunGen = false;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("application/octet-stream;charset=utf-8");
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);
		int nStart = 0;
		int nCount = WebSetting.nDefPageCount;
		int nPage = 1;

		boolean bRefrash = true;
		if (req.getParameter("refrash") != null)
			bRefrash = true;

		String strCategory = WebSetting.strDefaultCategory;

		if (req.getParameter("page") != null) {
			nPage = Integer.valueOf(req.getParameter("page").toString());
			nStart = (nPage - 1) * nCount;
			nCount = nStart + nCount;
		}

		if (req.getParameter("category") != null)
			strCategory = req.getParameter("category").toString();

		Date dateNow = new Date();

		if (nPage < 10 && nPage > 0 && bRefrash == false) {
			if ((dateNow.getTime() - WebSetting.arrListNewCheckSum[nPage - 1]) < WebSetting.timeGetNewGapTime
					&& WebSetting.arrListNewString[nPage - 1] != null) {
				GlobalsFun.WriteBuffer(
						resp,
						ZLibUtils
								.compress(WebSetting.arrListNewString[nPage - 1]
										.getBytes("UTF-8")));
				return;
			}
		}

		List<NewRssItem> listNews = NewDaoFactory.queryNewRssItemsByTitle(
				strCategory, nStart, nCount);

		String strlogo = "";
		String strReturnText = "";
		if (listNews != null) {

			for (NewRssItem item : listNews) {
				if (strlogo.length() == 0)
					strlogo = item.getLogo();
				strReturnText += String.format(WebSetting.strItemFormat,
						item.getId(), item.getNewTitle(),
						item.getInputDateStr());
			}
			String strSaveString = String.format(WebSetting.strNewXmlFormat,
					strCategory, strlogo, strReturnText);
			if (nPage < 10 && nPage > 0) {
				WebSetting.arrListNewString[nPage - 1] = strSaveString;
				WebSetting.arrListNewCheckSum[nPage - 1] = dateNow.getTime();
			}
			GlobalsFun.WriteBuffer(resp,
					ZLibUtils.compress(strSaveString.getBytes("UTF-8")));
		}
	}

	

}
